package com.hmdp.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * 封装的redis工具
 *  - 生成唯一id
 */
@Slf4j
@Component
public class RedisIdWorker {
    //    2018年6月25日00:00从 Unix 纪元 1970-01-01T00:00:00Z 开始的秒数的
    private static final long BEGIN_TIMESTAMP = 1529884800L;
    private static final int COUNT_BITS = 32;
    private final StringRedisTemplate stringRedisTemplate;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

//    public static void main(String[] args) {
//        LocalDateTime time = LocalDateTime.of(2018, 6, 25, 0, 0, 0);
//        long seconds = time.toEpochSecond(ZoneOffset.UTC);
//        System.out.println(seconds);//1529884800L
//    }

    public long nextId(String keyPrefix) {
        //生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSeconds = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSeconds - BEGIN_TIMESTAMP;//当前时间戳减去开始时间戳，得到时间差值

//        生成序列号
//        获取当前时间，精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //自增长
//        以不同业务和日期为key值
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
//        log.info("count:" + count);
        //返回
        return timestamp << COUNT_BITS | count;
    }
}
